# -*- encoding: utf-8 -*-
from openerp.osv import osv
import threading
from openerp import pooler
    
##=======重算焊点数向导=======##
class bom_solder_calc(osv.osv_memory):
    _name = "bom.solder.calc"
    _description = "BOM solder calculation batch"
    
    def do_solder_calc(self, cr, uid, ids, context=None):
        bom_ids = context and context.get('active_ids')
        if not bom_ids or len(bom_ids) > 10:
            #超过10个或者没有active_ids参数(计算所有BOM)
            threaded_calculation = threading.Thread(target=self.do_calc_solder_all, args=(cr, uid, ids, bom_ids, context))
            threaded_calculation.start()
        else:
            self.pool.get('mrp.bom').compute_solder_cnt(cr, uid, bom_ids, context=context)
        return {'type': 'ir.actions.act_window_close'} 
    
    def do_calc_solder_all(self, cr_old, uid, ids, bom_ids_calc, context=None):
        cr = pooler.get_db(cr_old.dbname).cursor()
        bom_ids = bom_ids_calc or self.pool.get('mrp.bom').search(cr, uid, [('bom_id','=',False)], context={'active_test':False})
        #单个循环计算
        for bom_id in bom_ids:
            self.pool.get('mrp.bom').compute_solder_cnt(cr, uid, [bom_id], context=context)
            cr.commit()
        cr.close()